package com.quanyan.pay.service.impl;

import com.quanyan.api.APIResponse;
import com.quanyan.common.encrypt.AESCoder;
import com.quanyan.orderpay.response.RespWeichatAccount;
import com.quanyan.pay.entity.WeichatAccount;
import com.quanyan.pay.mapper.WeichatAccountMapper;
import com.quanyan.pay.service.PayService;
import com.quanyan.pay.service.WeichatAccountService;
import com.quanyan.weichat.common.Configure;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.ByteArrayInputStream;

/**
 * Created by Zheng.Ke
 * Date 2016/7/28.
 */
@Service
public class WeichatAccountServiceImpl implements WeichatAccountService {
    private Logger logger = LoggerFactory.getLogger(WeichatAccountServiceImpl.class);

    @Value("${wechat.pay.callback}")
    private String WECHAT_PAY_CALLBACK;
    @Autowired
    private WeichatAccountMapper weichatAccountMapper;
    @Autowired
    private PayService payService;


    @Override
    public Configure getWeichatConfigure(Integer aId, boolean needCert) {
        WeichatAccount weichatAccount = this.weichatAccountMapper.selectByPrimaryKey(aId);
        weichatAccount.setWxKey(AESCoder.decodeContent(weichatAccount.getWxKey()));
        return getWeichatConfigure(weichatAccount, needCert);
    }

    @Override
    public Configure getWeichatConfigure(WeichatAccount weichatAccount, boolean needCert) {
        Configure.Builder builder = new Configure.Builder();
        logger.debug("wechat pay call back : " + WECHAT_PAY_CALLBACK);
        builder.setAppID(weichatAccount.getAppId())
                .setMchID(weichatAccount.getMchId())
                .setKey(weichatAccount.getWxKey())
                .setNOTIFY_URL(WECHAT_PAY_CALLBACK);
        if (needCert) {
            builder.setCertData(new ByteArrayInputStream(weichatAccount.getCertData()));
            builder.setCertPassword(AESCoder.decodeContent(weichatAccount.getCertPasswd()));
        }
        return builder.build();
    }

    @Override
    public WeichatAccount getWeichatConfigure(String mchId, int payId) {
        APIResponse<WeichatAccount> apiResponse = payService.getWeichatAccount(mchId, payId);
        return apiResponse.getData();
    }
}
